package com.test.nio.demo02;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;


public class SocketChannelDemo2 {
	
	void startClient() throws IOException, InterruptedException{
		SocketChannel socketChannel = SocketChannel.open();
		socketChannel.connect(new InetSocketAddress("localhost", 8999));
		// 注意客户端 要设置成阻塞状态 才能收到消息
//		socketChannel.configureBlocking(false);  
		
		String request = "Hello ServerSocketChannel 发送请求";
		ByteBuffer buff = ByteBuffer.wrap(request.getBytes("UTF-8"));
		socketChannel.write(buff);
		buff.clear();
		
		
		ByteBuffer rbuff = ByteBuffer.allocate(48);
		int size = socketChannel.read(rbuff);
		while(size>0){
			rbuff.flip();
			Charset charset = Charset.forName("UTF-8");
			System.out.print(charset.newDecoder().decode(rbuff));
			rbuff.clear();
			size = socketChannel.read(rbuff);
		}
		rbuff.clear();
//		socketChannel.close();
		Thread.sleep(5000);
	}
	
	public static void main(String[] args) throws IOException, InterruptedException {
		new SocketChannelDemo2().startClient();
	}
}
